package com.xxxtea.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxxtea.common.Result;
import com.xxxtea.dto.PageQuery;
import com.xxxtea.entity.Collect;
import com.xxxtea.entity.Dish;
import com.xxxtea.entity.Merchant;
import com.xxxtea.entity.SecondhandGoods;
import com.xxxtea.service.CollectService;
import com.xxxtea.service.DishService;
import com.xxxtea.service.MerchantService;
import com.xxxtea.service.SecondhandGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏控制器
 *
 * 提供收藏的完整管理功能，包括：
 * - 收藏的增删改查
 * - 收藏状态切换（收藏/取消收藏）
 * - 分页与列表查询
 * - 收藏对象类型多态处理（菜品、商家、旧物）
 *
 * 使用Swagger注解进行API文档生成
 * 使用Lombok注解简化代码
 *
 * @author badman
 * @since 1.0.0
 */
@Slf4j
@Api("收藏接口")
@RestController
@RequestMapping("/collect")
public class CollectController {
	/**
	 * 菜品服务
	 */
	@Resource
	private DishService dishService;
	
	/**
	 * 收藏服务
	 */
	@Resource
	private CollectService collectService;
	
	/**
	 * 商家服务
	 */
	@Resource
	private MerchantService merchantService;
	
	/**
	 * 旧物商品服务
	 */
	@Resource
	private SecondhandGoodsService secondhandGoodsService;

	/**
	 * 新增收藏/取消收藏
	 * 若已收藏则取消收藏，否则新增收藏
	 *
	 * @param request 收藏信息
	 * @return 操作结果
	 */
	@PostMapping
	@ApiOperation("新增收藏")
	public Result<String> save(@RequestBody Collect request) {
		boolean remove = collectService.remove(new LambdaQueryWrapper<Collect>()
				.eq(Collect::getBusinessType, request.getBusinessType())
				.eq(Collect::getBusinessId, request.getBusinessId())
		);
		if (remove) {
			return Result.success("已取消收藏");
		}
		collectService.save(request);
		return Result.success("已成功收藏");
	}

	/**
	 * 删除收藏
	 *
	 * @param id 收藏ID
	 * @return 操作结果
	 */
	@DeleteMapping("/{id}")
	@ApiOperation("删除收藏")
	public Result<String> delete(@PathVariable String id) {
		if (!collectService.removeById(id)) {
			return Result.error("删除失败!");
		}
		return Result.success();
	}

	/**
	 * 更新收藏
	 *
	 * @param request 收藏信息
	 * @return 操作结果
	 */
	@PutMapping
	@ApiOperation("更新收藏")
	public Result<String> update(@RequestBody Collect request) {
		if (!collectService.updateById(request)) {
			return Result.error("更新失败!");
		}
		return Result.success();
	}

	/**
	 * 获取单个收藏
	 *
	 * @param id 收藏ID
	 * @return 收藏信息
	 */
	@GetMapping("/{id}")
	@ApiOperation("获取单个收藏")
	public Result<Collect> getOne(@PathVariable String id) {
		return Result.success(collectService.getById(id));
	}

	/**
	 * 获取收藏列表
	 *
	 * @param request 查询条件
	 * @return 收藏列表
	 */
	@GetMapping("/list")
	@ApiOperation("获取收藏列表")
	public Result<List<Collect>> list(Collect request) {
		LambdaQueryWrapper<Collect> wrapper = new LambdaQueryWrapper<>(request);
		return Result.success(collectService.list(wrapper));
	}

	/**
	 * 分页查询收藏
	 * 支持多类型收藏对象的多态返回
	 *
	 * @param request 分页查询条件
	 * @return 分页收藏对象列表
	 */
	@PostMapping("/page")
	@ApiOperation("分页查询收藏")
	public Result<Page<?>> page(@RequestBody PageQuery<Collect> request) {
		// 分页查询
		Collect param = request.getParam();
		LambdaQueryWrapper<Collect> wrapper = new LambdaQueryWrapper<>(param);
		Page<Collect> pageResult = collectService.page(request.toPage(), wrapper);
		if (pageResult.getRecords().isEmpty()) {
			return Result.success(pageResult);
		}

		List<Integer> ids = pageResult.getRecords().stream().map(Collect::getBusinessId).collect(Collectors.toList());
		if (param.getBusinessType() == Collect.BusinessType.DISH) {
			List<Dish> list = dishService.listByIds(ids);
			list.forEach(e -> e.setCollect(true));
			return Result.success(new Page<Dish>(pageResult.getCurrent(), pageResult.getSize()).setRecords(list));
		}
		if (param.getBusinessType() == Collect.BusinessType.MERCHANT) {
			List<Merchant> list = merchantService.listByIds(ids);
			list.forEach(e -> e.setCollect(true));
			return Result.success(new Page<Merchant>(pageResult.getCurrent(), pageResult.getSize()).setRecords(list));
		}
		if (param.getBusinessType() == Collect.BusinessType.PRODUCT) {
			List<SecondhandGoods> list = secondhandGoodsService.listByIds(ids);
			list.forEach(e -> e.setCollect(true));
			return Result.success(new Page<SecondhandGoods>(pageResult.getCurrent(), pageResult.getSize()).setRecords(list));
		}
		return Result.success(pageResult);
	}
}
